<template>
  <div class="user-settings">
    <div class="settings-content">
      <!-- 基本信息设置 -->
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <div class="title-section">
              <el-icon class="title-icon"><User /></el-icon>
              <span class="card-title">基本信息</span>
            </div>
            <el-button type="primary" link @click="editBasicInfo" class="edit-btn">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
          </div>
        </template>

        <div class="basic-info">
          <div class="avatar-section">
            <div class="avatar-container">
              <el-avatar :size="140" :src="userInfo.avatar" class="user-avatar" />
              <div class="avatar-overlay" @click="showAvatarUpload = true">
                <el-icon><Camera /></el-icon>
                <span>更换头像</span>
              </div>
            </div>
            <div class="avatar-info">
              <h3 class="username">{{ userInfo.username }}</h3>
              <el-tag 
                :type="userInfo.type === 'farmer' ? 'success' : 'primary'" 
                class="user-type-tag"
                effect="light"
              >
                {{ userInfo.type === 'farmer' ? '👨‍🌾 农户' : '👨‍💼 买家' }}
              </el-tag>
            </div>
          </div>

          <div class="info-details">
            <div class="info-grid">
              <div class="info-item">
                <div class="info-icon">
                  <el-icon><Calendar /></el-icon>
                </div>
                <div class="info-content">
                  <label class="info-label">注册时间</label>
                  <span class="info-value">{{ formatDate(userInfo.createTime) }}</span>
                </div>
              </div>
              <div class="info-item">
                <div class="info-icon">
                  <el-icon><Clock /></el-icon>
                </div>
                <div class="info-content">
                  <label class="info-label">最后登录</label>
                  <span class="info-value">{{ formatDate(userInfo.lastLoginTime) }}</span>
                </div>
              </div>
              <div class="info-item">
                <div class="info-icon">
                  <el-icon><Message /></el-icon>
                </div>
                <div class="info-content">
                  <label class="info-label">邮箱</label>
                  <span class="info-value">{{ userInfo.email || '未绑定' }}</span>
                </div>
              </div>
              <div class="info-item">
                <div class="info-icon">
                  <el-icon><Iphone /></el-icon>
                </div>
                <div class="info-content">
                  <label class="info-label">手机</label>
                  <span class="info-value">{{ userInfo.phone || '未绑定' }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 修改用户名对话框 -->
    <el-dialog
      v-model="showEditUsername"
      title="修改用户名"
      width="500px"
      :close-on-click-modal="false"
      class="custom-dialog"
    >
      <div class="dialog-header">
        <el-icon class="dialog-icon"><EditPen /></el-icon>
        <span>修改用户名</span>
      </div>
      
      <el-form
        ref="usernameFormRef"
        :model="usernameForm"
        :rules="usernameRules"
        label-width="80px"
        class="dialog-form"
      >
        <el-form-item label="新用户名" prop="username">
          <el-input
            v-model="usernameForm.username"
            placeholder="请输入新的用户名"
            maxlength="20"
            show-word-limit
            size="large"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditUsername = false" size="large">取消</el-button>
        <el-button type="primary" @click="updateUsername" :loading="submitting" size="large">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="showAvatarUpload"
      title="更换头像"
      width="480px"
      :close-on-click-modal="false"
      class="custom-dialog"
    >
      <div class="dialog-header">
        <el-icon class="dialog-icon"><Camera /></el-icon>
        <span>更换头像</span>
      </div>
      
      <div class="avatar-upload-dialog">
        <div class="avatar-preview">
          <div class="preview-container">
            <el-avatar :size="180" :src="avatarPreview || userInfo.avatar" class="preview-avatar" />
            <div class="preview-overlay" v-if="avatarPreview">
              <el-icon><View /></el-icon>
            </div>
          </div>
        </div>
        
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="handleAvatarUpload"
          accept="image/jpeg,image/png,image/gif"
        >
          <el-button type="primary" size="large" class="upload-btn">
            <el-icon><Upload /></el-icon>
            选择图片
          </el-button>
        </el-upload>
        
        <div class="upload-tips">
          <div class="tip-item">
            <el-icon><InfoFilled /></el-icon>
            <span>支持 JPG、PNG、GIF 格式</span>
          </div>
          <div class="tip-item">
            <el-icon><InfoFilled /></el-icon>
            <span>大小不超过 2MB</span>
          </div>
          <div class="tip-item">
            <el-icon><InfoFilled /></el-icon>
            <span>建议尺寸：200x200 像素</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showAvatarUpload = false" size="large">取消</el-button>
        <el-button 
          type="primary" 
          @click="updateAvatar" 
          :disabled="!newAvatarFile"
          :loading="submitting"
          size="large"
        >
          保存头像
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Edit, Camera, Upload, EditPen, Calendar, Clock, Message, Iphone, View, InfoFilled } from '@element-plus/icons-vue'

// 响应式数据
const showEditUsername = ref(false)
const showAvatarUpload = ref(false)
const submitting = ref(false)

const usernameFormRef = ref(null)

// 用户信息
const userInfo = ref({
  id: 1,
  username: '农户张三',
  avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
  type: 'farmer',
  email: 'zhangsan@example.com',
  phone: '138****1234',
  createTime: '2024-01-01T10:00:00Z',
  lastLoginTime: '2024-12-01T15:30:00Z'
})

// 表单数据
const usernameForm = reactive({
  username: ''
})

const avatarPreview = ref('')
const newAvatarFile = ref(null)

// 表单验证规则
const usernameRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 方法
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

const editBasicInfo = () => {
  usernameForm.username = userInfo.value.username
  showEditUsername.value = true
}

const updateUsername = async () => {
  if (!usernameFormRef.value) return
  
  try {
    await usernameFormRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    userInfo.value.username = usernameForm.username
    ElMessage.success('用户名修改成功')
    showEditUsername.value = false
  } catch (error) {
    console.error('修改用户名失败:', error)
  } finally {
    submitting.value = false
  }
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isGIF = file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG && !isGIF) {
    ElMessage.error('头像图片只能是 JPG/PNG/GIF 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarUpload = (options) => {
  const file = options.file
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target.result
    newAvatarFile.value = file
  }
  reader.readAsDataURL(file)
}

const updateAvatar = async () => {
  if (!newAvatarFile.value) return
  
  submitting.value = true
  try {
    userInfo.value.avatar = avatarPreview.value
    ElMessage.success('头像更新成功')
    showAvatarUpload.value = false
    newAvatarFile.value = null
  } catch (error) {
    console.error('更新头像失败:', error)
    ElMessage.error('更新头像失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadUserSettings()
})

const loadUserSettings = async () => {
  try {
    // 模拟加载用户设置
  } catch (error) {
    console.error('加载用户设置失败:', error)
  }
}
</script>

<style scoped>
.user-settings {
  width: 100%;
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  min-height: 100vh;
}

.settings-content {
  max-width: 1000px;
  margin: 0 auto;
}

.settings-card {
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: none;
  overflow: hidden;
  background: white;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 24px;
  color: white;
}

.card-title {
  font-size: 20px;
  font-weight: 700;
  color: white;
  letter-spacing: 0.5px;
}

.edit-btn {
  color: white;
  font-weight: 500;
}

.edit-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

/* 基本信息样式 */
.basic-info {
  padding: 40px;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 32px;
  margin-bottom: 40px;
  padding: 32px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%);
  border-radius: 20px;
  border: 1px solid #e8eaff;
}

.avatar-container {
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.3);
}

.user-avatar {
  border: 4px solid white;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(102, 126, 234, 0.8);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all 0.3s ease;
  border-radius: 50%;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
  transform: scale(1.05);
}

.avatar-overlay .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.avatar-overlay span {
  font-size: 14px;
  font-weight: 500;
}

.avatar-info {
  flex: 1;
}

.username {
  font-size: 28px;
  font-weight: 700;
  color: #2d3748;
  margin: 0 0 12px 0;
}

.user-type-tag {
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: 600;
}

/* 信息网格样式 */
.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.info-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  border-color: #667eea;
}

.info-icon {
  width: 56px;
  height: 56px;
  border-radius: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  flex-shrink: 0;
}

.info-content {
  flex: 1;
}

.info-label {
  display: block;
  color: #718096;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 6px;
}

.info-value {
  display: block;
  color: #2d3748;
  font-size: 16px;
  font-weight: 600;
}

/* 对话框样式 */
.custom-dialog {
  border-radius: 20px;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.dialog-icon {
  font-size: 24px;
  color: #667eea;
}

.dialog-form {
  padding: 20px 0;
}

/* 头像上传对话框样式 */
.avatar-upload-dialog {
  text-align: center;
  padding: 20px 0;
}

.avatar-preview {
  margin-bottom: 32px;
}

.preview-container {
  position: relative;
  display: inline-block;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

.preview-avatar {
  border: 6px solid white;
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(102, 126, 234, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 32px;
}

.upload-btn {
  border-radius: 12px;
  padding: 12px 32px;
  font-weight: 600;
}

.upload-tips {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #718096;
  font-size: 14px;
}

.tip-item .el-icon {
  color: #667eea;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-settings {
    padding: 16px;
  }
  
  .basic-info {
    padding: 24px;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
    gap: 24px;
    padding: 24px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .info-item {
    padding: 20px;
  }
  
  .card-header {
    padding: 16px 20px;
  }
  
  .card-title {
    font-size: 18px;
  }
}
</style>